/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

package com.tbit.main.service.impl;

import com.tbit.common.entity.TempPowerCheckResult;
import com.tbit.main.constant.RedisConstant;
import com.tbit.main.controller.interceptor.LoginUserContextHolder;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.MachineStatus;
import com.tbit.main.pojo.VO.TempPowerCheckReqVO;
import com.tbit.main.pojo.VO.TempPowerOnReqVO;
import com.tbit.main.remote.rpc.UQHttpClient;
import com.tbit.main.service.MachineStatusService;
import com.tbit.main.service.RedisService;
import com.tbit.main.service.TempPowerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author yao
 * @since 2024/7/4 16:48
 */
@Service
@Slf4j
@Validated
public class TempPowerServiceImpl implements TempPowerService {

    @Resource
    private MachineStatusService machineStatusService;
    @Resource
    private RedisService redisService;

    @Override
    @SuppressWarnings("unchecked")
    public TempPowerCheckResult checkTempPower(TempPowerCheckReqVO reqVO) {
        MachineStatus machineStatus = machineStatusService.getByMachineId(reqVO.getMachineId());

        if (machineStatus == null) {
            throw new BaseException("MachineState.not.gps");
        }

        reqVO.setLat(machineStatus.getLat());
        reqVO.setLon(machineStatus.getLon());

        Map<String, Object> params = BeanMap.create(reqVO);

        return UQHttpClient.checkTempPower(params);
    }

    @Override
    @SuppressWarnings("unchecked")
    public void powerOn(TempPowerOnReqVO reqVO) {
        reqVO.setOpId(LoginUserContextHolder.getLoginUserId());
        Map<String, Object> params = BeanMap.create(reqVO);
        if (Objects.nonNull(reqVO.getCountDown())) {
            redisService.add(RedisConstant.TEMP_POWER_KEY + reqVO.getUserId(), reqVO.getCountDown().toString(), reqVO.getCountDown(), TimeUnit.MINUTES);
        }
        UQHttpClient.powerOn(params);
    }
}
